<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Http\Controllers\Controller;
use App\Http\Resources\UserCouponResource;
use App\Models\UserCoupon;
use Illuminate\Support\Str;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use App\Http\Requests\Api\VerifyRequest;
use App\Http\Requests\Api\WriteOffRecordRequest;

class UserCouponController extends Controller
{
    public function show($id, UserCoupon $userCoupon)
    {
        $row = $userCoupon->where('id', $id)->with('dealer')->firstOrFail();
        $this->authorize('own', $row);
        $key = 'dfjk-' . $row->user_id . '-' . Str::random(5);
        $expiredAt = Carbon::now()->addMinutes(1);
        Cache::put($key, ['model' => 'UserCoupon', 'code' => $row->code, 'user_id' => $row->user_id], $expiredAt);
        $qrcode = app('qrcode')->format('png')
            ->size(150)
            ->margin(0)
            ->errorCorrection('H')
            ->generate($key);

        $data = [
            'key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
            'image' => base64_encode($qrcode)
        ];
        $row->setAttribute('qrcode', $data);
        return $this->resource(new UserCouponResource($row));
    }

    public function getCouponByKey(Request $request, UserCoupon $userCoupon)
    {
        $cache = Cache::get($request->key);
        if (!$cache) {
            return $this->failed('model-not-found-exception', '无效的key');
        }
        $coupon = $userCoupon->where('code', $cache['code'])->firstOrFail();
        return $this->resource(new UserCouponResource($coupon));
    }

    public function verify(VerifyRequest $request)
    {
        $coupon = UserCoupon::where('code', $request->code)->firstOrFail();
        $result = app('CouponService')->verify($coupon, $request->dealer_code, $request->org_id);
        return $this->resource(new UserCouponResource($result));
    }

    //核销记录
    public function writeOffRecord(WriteOffRecordRequest $request)
    {
        $query = UserCoupon::where('org_id', $request->org_id)->where('used_at', '<', $request->at)->whereNotNull('used_at')->orderBy('used_at', 'desc')->with('user');
        if ($request->search) {
            if (is_phone($request->search)) {
                $user_id = User::where('phone', $request->search)->value('id');
                $query = $query->where('user_id', $user_id);
            } else {
                $query = $query->where('title', 'like', '%' . $request->search . '%')->orWhere('code', 'like', '%' . $request->search . '%');
            }
        }
        $coupons = $query->take(10)->get();
        return $this->resource(UserCouponResource::collection($coupons));
    }
}
